from player import Minimax
import sys

infinity = sys.maxint

class AlphaBeta(Minimax):
    def get_move(self,board):
        return self.alphabeta(board,self.ply)

    def alphabeta(self,board,ply):
        best_move = None
        best_val = -infinity
        for move in board.legal_moves():
            b = board.copy()
            b.make_move(move)
            val = -1 * self.alphabeta_value(b,ply-1,-infinity,infinity)[0]
            if val > best_val:
                best_val = val
                best_move = move
        return best_move


    def alphabeta_value(self,board,ply,alpha,beta):
        if ply==0 or board.game_over():
            a = self.eval_fn(board,1)
            #print a
            return (a,None)
        for move in board.legal_moves():
            #b = board.copy()
            b = board.copy()
            #print oldboard is not board
            b.make_move(move)
            #print self.alphabeta_value(b,ply-1,-beta,-alpha)
            val = -1 * self.alphabeta_value(b,ply-1,-beta,-alpha)[0]
            #print val
            if val >= beta:
                #print 'Beta was exceeded : %d>%d At ply:%d' % (val, beta, ply)
                return (beta, move)
            if val > alpha:
                alpha = val
                #print 'Alpha increased to', alpha
        return (alpha, move)
